<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href>商品管理</a>
      </el-breadcrumb-item>
      <el-breadcrumb-item>添加优惠券</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card v-loading="loading">
      <!-- 提示区域 -->
      <el-alert title="添加优惠券信息" type="info" center show-icon :closable="false"></el-alert>
      <!-- 步骤条区域 -->
      <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="使用范围"></el-step>
        <el-step title="其它设置"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- 表单区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <!-- tab栏区域 -->
        <el-tabs
          :tab-position="'left'"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="名称:" prop="name">
              <el-input v-model="addForm.name"></el-input>
            </el-form-item>
            <el-form-item label="面值:" prop="faceValue">
              <el-input v-model="addForm.faceValue" type="number"></el-input>
            </el-form-item>
            <el-form-item label="满减值:" prop="how_much">
              <el-input v-model="addForm.how_much" type="number"></el-input>
            </el-form-item>
            <el-form-item label="叠加使用:">
              <!-- 作用域插槽 -->
              <template slot-scope>
                <el-switch v-model="addForm.stackUsing"></el-switch>
              </template>
            </el-form-item>
            <el-form-item label="位置:" prop="position">
              <el-input v-model="addForm.position" type="number"></el-input>
            </el-form-item>
            <el-form-item label="使用提示:" prop="usingTips">
              <el-input v-model="addForm.usingTips"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="使用范围" name="1">
            <el-form-item label="使用范围:">
              <el-select
                v-model="addForm.useScope"
                placeholder="请选择优惠券可使用抵扣的范围"
                @change="selectUseScope(addForm.useScope)"
              >
                <el-option
                  v-for="item in useScope"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品品类:">
              <el-select v-model="addForm.productClass" placeholder="请选择可抵扣的商品的品类">
                <el-option
                  v-for="item in classfication"
                  :key="item.name"
                  :label="item.name"
                  :value="item.name"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="可抵扣商品:">
              <el-checkbox-group v-model="selectGoodsArr">
                <el-checkbox
                  v-for="(item) in activityItemList"
                  :label="item.name"
                  :value="item._id"
                  :key="item._id"
                  checked
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <!-- 用户列表区域 -->
            <el-table :data="goodsList" border stripe @selection-change="handleSelectionChange">
              <el-table-column type="selection" label="#"></el-table-column>
              <el-table-column label="商品名称" prop="name"></el-table-column>
              <el-table-column label="商品价格(元)" prop="price" width="100px"></el-table-column>
              <el-table-column label="库存状态" prop="stock" width="90px"></el-table-column>
              <el-table-column label="商品分类" prop="category" width="90px"></el-table-column>

              <el-table-column label="使用优惠券" width="90px">
                <!-- 作用域插槽 -->
                <template slot-scope="scope">
                  <el-switch v-model="scope.row.coupon" @change="couponStateChange(scope.row)"></el-switch>
                </template>
              </el-table-column>

              <el-table-column label="创建时间" prop="createTime" width="140px">
                <template slot-scope="scope">{{scope.row.createTime | dateFormat}}</template>
              </el-table-column>

              <el-table-column label="上架状态" width="90px">
                <!-- 作用域插槽 -->
                <template slot-scope="scope">
                  <el-switch
                    v-model="scope.row.upper_shelf"
                    @change="upperShelfStateChange(scope.row)"
                  ></el-switch>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页区域 -->
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="queryInfo.pageNum"
              :page-sizes="[5, 10, 15, 20]"
              :page-size="queryInfo.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
            ></el-pagination>
          </el-tab-pane>
          <el-tab-pane label="其它设置" name="2">
            <el-form-item label="使用有效期:">
              <!-- <el-input v-model="addForm.termOfValidity" type="number"></el-input> -->
              <el-select v-model="addForm.effectiveDays" placeholder="领取优惠券过期的天数">
                <el-option
                  v-for="item in termOfValidityOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="上架有效期:">
              <!-- <el-input v-model="addForm.termOfValidity" type="number"></el-input> -->
              <el-select v-model="addForm.termOfValidity" placeholder="优惠券生成后过期天数">
                <el-option
                  v-for="item in termOfValidityOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="优惠券上下架:">
              <!-- 作用域插槽 -->
              <template slot-scope>
                <el-switch v-model="addForm.upShelves"></el-switch>
              </template>
            </el-form-item>
            <el-button size="small" type="primary" @click="addCoupon">添加优惠券</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import { getClassfication, getGoodsList, addCoupon } from '../../api/coupon/add.js'
export default {
  data() {
    return {
      loading: false,
      activeIndex: '0',
      //   图片预览图片路径名称
      previewPath: '',
      //   图片预览框显示 与 关闭
      previewVisible: false,
      //   添加商品的表单数据对象
      addForm: {
        name: '',
        faceValue: 0,
        how_much: 0,
        stackUsing: false,
        usingTips: '',
        position: 0,
        useScope: 3,
        productClass: '',
        // 品类抵扣，可抵扣的商品数组
        productId: [],
        effectiveDays: 0,
        termOfValidity: 0,
        upShelves: false
      },
      goodsList: [],
      //   优惠券使用范围
      useScope: [
        {
          value: 1,
          label: '单品商品抵扣'
        },
        {
          value: 2,
          label: '商品品类抵扣'
        },
        {
          value: 3,
          label: '所有商品均可抵扣'
        }
      ],
      classfication: [],
      categoryList: [],
      activityItemList: [],
      // 有效期选项
      termOfValidityOptions: [
        {
          value: '5',
          label: '五天'
        },
        {
          value: '10',
          label: '十天'
        },
        {
          value: '30',
          label: '一个月'
        },
        {
          value: '60',
          label: '两个月'
        },
        {
          value: '90',
          label: '三个月'
        },
        {
          value: '180',
          label: '六个月'
        },
        {
          value: '365',
          label: '一年'
        },
        {
          value: '730',
          label: '两年'
        },
        {
          value: '1095',
          label: '三年'
        }
      ],
      queryInfo: {
        query: null,
        // 当前的页数
        pageNum: 1,
        // 当前每页显示多少条
        pageSize: 5
      },
      total: 0,
      selectGoodsArr: [],
      //  是否显示商品品类抵扣选择器
      selectGoodsCategoryVisible: true,
      //   图片上传组件的headers请求头对象（里面可以包含Token）
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      //   表单验证规则
      addFormRules: {
        name: [
          { required: true, message: '请输入优惠券名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        faceValue: [
          { required: true, message: '请输入优惠券面值', trigger: 'blur' }
        ],
        how_much: [
          { required: true, message: '请输入优惠券满减值', trigger: 'blur' }
        ],
        position: [
          { required: true, message: '请输入优惠券展示位置', trigger: 'blur' }
        ],
        usingTips: [
          {
            required: true,
            message: '请输入优惠券使用提示信息',
            trigger: 'blur'
          },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {},
  methods: {
    //   选择抵扣范围变化事件
    selectUseScope(value) {
      //  专属抵扣
      console.log('您先择啦优惠券的抵扣范围')
      console.log(value)
      if (value === 1) {
        this.selectGoodsCategoryVisible = true
        this.addForm.productClass = ''
        // this.addForm.productId = []
        this.cleselectGoodsCategory()
        this.getGoods()
      } else if (value === 2) {
        //  品类抵扣
        this.selectGoodsCategoryVisible = false
        this.activityItemList = []
        this.addForm.productId = []
        this.goodsList = []
        this.total = 0
      } else if (value === 3) {
        //  无门槛，所有商品均可抵扣
        this.selectGoodsCategoryVisible = true
        this.activityItemList = []
        this.goodsList = []
        this.addForm.productClass = ''
        this.addForm.productId = []
        this.total = 0
      }
    },
    //   商品品类选择框清除事件
    cleselectGoodsCategory() {
      console.log('这里是清除选择商品品类后的事件')
    },
    //  取商品列表
    getGoods() {
      this.loading = true
      getGoodsList(this.queryInfo).then(res => {
        this.loading = false
        console.log(res.data)
        if (!res.data.success) {
          return this.$message.error('获取商品列表失败')
        }
        this.goodsList = res.data.data
        console.log(this.goodsList)
        this.total = res.data.Total
        console.log('total:' + this.total)
      })
    },
    beforeTabLeave(activeName, oldActiveName) {
      console.log(activeName, oldActiveName)
      //   if (oldActiveName === '0' && !this.addForm.category) {
      //     this.$message.error('还未选择商品分类')
      //     return false
      //   } else {
      //   }
    },
    tabClicked() {
      console.log(this.activeIndex)
      if (this.activeIndex === '1') {
        console.log('获取商品品类')
        // 获取商品品类
        getClassfication().then(res => {
          console.log(res.data)
          if (!res.data.success) {
            return this.$message.error('获取商品分类列表失败')
          }
          this.classfication = res.data.data
          console.log(this.classfication)
        })
      } else if (this.activeIndex === '2') {
        console.log(this.addForm)
      } else if (this.activeIndex === '3') {
        console.log(this.addForm)
      }
    },
    // 监听 pageSize 改变事件
    handleSizeChange(newSize) {
      console.log(newSize)
      this.queryInfo.pageSize = newSize
      this.getGoods()
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      console.log(newPage)
      this.queryInfo.pageNum = newPage
      //   console.log(this.queryInfo.pageNum)
      this.getGoods()
    },
    // 监听商品列表里的商品被选中事件
    handleSelectionChange(val) {
      if (val.length > 0) {
        console.log(val)
        // 判断是否有商品不可使用优惠券商品，如果有给于提示
        for (let i = 0; i < val.length; i++) {
          if (!val[i].coupon) {
            return this.$message.error(
              '您选择的商品<' +
                val[i].name +
                '> ,此为不可使用使用优惠券的商品！！'
            )
          }
        }
        // 加入到数组里
        for (let i = 0; i < val.length; i++) {
          if (this.activityItemList.length > 0) {
            let repeatData = false
            for (let n = 0; n < this.activityItemList.length; n++) {
              if (val[i]._id === this.activityItemList[n]._id) {
                repeatData = true
                break
              }
            }
            if (!repeatData) {
              this.activityItemList.push(val[i])
              this.addForm.productId.push(val[i]._id)
            }
          } else {
            this.activityItemList.push(val[i])
            this.addForm.productId.push(val[i]._id)
          }
        }
      }
    },
    // 添加优惠券
    addCoupon() {
      this.$refs.addFormRef.validate(valid => {
        if (!valid) {
          return this.$message.error('请填写必要的表单项！')
        }
        //  检查领券后的有效天数
        if (this.addForm.effectiveDays <= 0) {
          return this.$message.error('请选择领券后有效的天数！')
        }
        //  检查优惠券生成后的有效天数
        if (this.addForm.termOfValidity <= 0) {
          return this.$message.error('请选择优惠券生成后有效的天数！')
        }
        console.log(this.addForm)
        //  执行添加
        addCoupon(this.addForm).then(res => {
          console.log(res.data)
          if (res.data.success) {
            this.$message.success('优惠券添加成功')
            this.$router.push('/coupon')
          }
        })
      })
    }
  }
}
</script>
<style lang="less" scoped>
.el-checkbox {
  margin: 0 5px 0 0 !important ;
}
</style>
